/**
 */

package io.hugetower.modules.app.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.hugetower.common.utils.Constant;
import io.hugetower.common.utils.PageUtils;
import io.hugetower.common.utils.R;
import io.hugetower.common.validator.ValidatorUtils;
import io.hugetower.modules.app.form.LoginForm;
import io.hugetower.modules.app.service.UserService;
import io.hugetower.modules.app.utils.JwtUtils;
import io.hugetower.modules.pest.entity.CropPestDiseaseEntity;
import io.hugetower.modules.pest.service.CropPestDiseaseService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import org.apache.http.util.TextUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * APP登录授权
 *
 * @author Mark liuyan@hugetower.cn
 */
@RestController
@RequestMapping("/app")
@Api("APP接口")
public class AppController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private CropPestDiseaseService cropPestDiseaseService;



    /**
     * 上传病虫识别截图
     */
    @PostMapping("uploadPic")
    @ApiOperation("上传病虫识别截图")
    public R uploadPic(@RequestParam("file") MultipartFile file) throws IOException {

        String result=callPythonApiWithImage(file.getOriginalFilename(),file.getBytes());
        if (TextUtils.isEmpty(result)){
            return R.error("返回结果为空");
        }

        String[] parts = result.split("-");

        CropPestDiseaseEntity cropPestDiseaseEntity=cropPestDiseaseService.getOne(new QueryWrapper<CropPestDiseaseEntity>().like("name",parts.length>1?"%"+parts[parts.length-1]+"%":parts[0]),false);

        if (cropPestDiseaseEntity==null){
            return R.error("没有找到结果");
        }


        return R.ok().put("data",cropPestDiseaseEntity);
    }


    /**
     * 列表
     */
    @RequestMapping("/searchPestList")
    @ApiOperation("分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页码，从1开始", paramType = "query", required = true, dataType="int") ,
            @ApiImplicitParam(name = "limit", value = "每页显示记录数", paramType = "query",required = true, dataType="int")
    })
    //@RequiresPermissions("pest:croppestdisease:list")
    public R list(@ApiIgnore @RequestParam Map<String, Object> params, CropPestDiseaseEntity cropPestDiseaseEntity){
        PageUtils page = cropPestDiseaseService.queryPage(params, cropPestDiseaseEntity);

        return R.ok().put("data", page);
    }

    public static void main(String[] args) {
        String str = "叶斑病";
        String[] parts = str.split("-");
        for (String part : parts) {
            System.out.println(part);
        }
    }

    /**
     * 调用python api接口获取虫害识别结果
     * @param fileName
     * @param imageData
     * @throws IOException
     */
    public String callPythonApiWithImage(String fileName,byte [] imageData) throws IOException {
        String apiUrl = "http://localhost:5000/predict";

        RestTemplate restTemplate=new RestTemplate();

        // Step 2: Build the request entity with multi-part content
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        ByteArrayResource resource = new ByteArrayResource(imageData) {
            @Override
            public String getFilename() {
                return fileName;
            }
        };
        body.add("image", resource);

        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
        // Step 3: Call the Python API using RestTemplate

        String decodedPrediction="";
        try {
            ResponseEntity<String> response = restTemplate.postForEntity(apiUrl, requestEntity, String.class);
            // Step 4: Process the response
            System.out.println("Response Status Code: " + response.getStatusCode());
            System.out.println("Response Body: " + response.getBody());
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(response.getBody());
            decodedPrediction = jsonNode.get("prediction").asText();
            System.out.println(decodedPrediction);  // 输出：1-大豆-病害-叶斑病
        }catch (Exception e){
            System.out.println("调用Python识别接口出现异常："+e.getMessage());
        }

        return decodedPrediction;
    }


    /**
     * 将客户端发送的图片保存本地
     * @param file
     */
    void multiPartSaveToPic(MultipartFile file){
        // 1. 验证文件是否为空

        // 2. 设置文件保存路径（包括文件名）
        String fileName = file.getOriginalFilename();
        Path targetLocation = Paths.get("D:\\开发软件\\Postman6.1.4", fileName);

        // 3. 将MultipartFile保存到本地文件系统
        try {
            Files.copy(file.getInputStream(), targetLocation);
        } catch (IOException e) {

        }
    }





}
